package com.lemurian.bankdata.bean;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.lemurian.bankdata.bean.base.BaseDaoHibernate;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.entity.Client;
import com.lemurian.entity.Tax;

@Repository
public class TaxDAO extends BaseDaoHibernate<Tax>{
	
	private BankDataLogger log = BankDataLogger.getLogger(TaxDAO.class.getName());
	
	@Override
	public Tax findById(int id){
		log.info("Overide findById on TaxDAO, Get in");
		try {
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Tax.class);
			criteria.createAlias("client", "client");
			criteria.createCriteria("client.debitur", "debitur");
			
			criteria.add(Restrictions.eq("id", id));
			return (Tax) criteria.uniqueResult();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public PartialList<Tax> findByCriteria(int start, int count, Order order, Criterion... criterion){
		PartialList<Tax> partialList = null;
		try {
			log.info("Overide PartialList on TaxDAO, Get in");
			// total
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Tax.class);
			criteria.createCriteria("client", "client");
			criteria.createCriteria("client.debitur", "debitur");
			
			criteria.setCacheable(true);
			for (Criterion c : criterion) {
				criteria.add(c);
			}
			criteria.setProjection(Projections.rowCount());
			int total = ((Integer) criteria.list().iterator().next()).intValue();
			// partial data
			criteria = sessionFactory.getCurrentSession().createCriteria(Tax.class);
			criteria.createCriteria("client", "client");
			criteria.createCriteria("client.debitur", "debitur");
			criteria.setCacheable(true);
			for (Criterion c : criterion) {
				criteria.add(c);
			}
			if (order!=null) criteria.addOrder(order);
			criteria.setFirstResult(start);
			criteria.setMaxResults(count);
			
			partialList = new PartialList<Tax>(criteria.list(), total);
		} catch(Exception exception){
			exception.printStackTrace();
			//sessionFactory.getCurrentSession().getTransaction().rollback();
		}
		return partialList;
	}
	
	public Tax findTaxByClient(Client client) {
		try {
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Tax.class);
			criteria.createAlias("client", "client");
			criteria.createCriteria("client.debitur", "debitur");
			
			criteria.add(Restrictions.eq("client", client));
			Tax tax = (Tax) criteria.uniqueResult();
			if (tax != null) {
				return tax;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Tax();
	}
}